package cn.com.tcb.dxe.elec_mobile_native_plugin

import android.os.Handler
import android.os.Looper
import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar

/** ElecMobileNativePlugin */
public class ElecMobileNativePlugin: FlutterPlugin, MethodCallHandler {
  private val methodProcessorMap = HashMap<String, BaseMethodProcessor>()
  private val handler = Handler(Looper.getMainLooper()) {
    when(it.what) {
      ASYNC_COMPLETED -> {
        if(it.obj is AsyncResultCallback) {
          (it.obj as AsyncResultCallback).perform()
        }
      }
    }
    return@Handler false
  }

  init {
    instance = this
  }

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    val channel = MethodChannel(flutterPluginBinding.binaryMessenger, "elec_mobile_native_plugin_method_channel")
    channel.setMethodCallHandler(this)
  }

  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  companion object {
    private lateinit var instance : ElecMobileNativePlugin

    @JvmStatic
    fun addMethodProcess(processor: BaseMethodProcessor) {
      if(processor is AsyncMethodProcessor) {
        processor.handler = instance.handler
      }
      instance.methodProcessorMap[processor.methodName] = processor
    }

    @JvmStatic
    fun registerWith(registrar: Registrar, builder: ElecMobileNativePlugin.() -> Unit) {
      val channel = MethodChannel(registrar.messenger(), "elec_mobile_native_plugin_method_channel")
      val plugin = ElecMobileNativePlugin()
      builder(plugin)
      channel.setMethodCallHandler(plugin)
    }

    internal const val ASYNC_COMPLETED = 0
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    val methodProcessor = methodProcessorMap[call.method] ?: return result.notImplemented()
    methodProcessor.onMethodCall(call, result)
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
  }
}
